import { ref, computed } from "vue"
import dayjs from "dayjs"

export const useDateSelector = () => {
	// 当前选中的选项：今天、明天或指定日期
	const selectedType = ref<"today" | "tomorrow" | "custom">("today")
	// 如果是指定日期，存储具体日期
	const customDate = ref("")

	// 计算属性：当前选中的日期值，会随 selectedType 和 customDate 的变化而变化
	const selectedDate = computed(() => {
		switch (selectedType.value) {
			case "today":
				return dayjs().format("YYYY-MM-DD")
			case "tomorrow":
				return dayjs().add(1, "day").format("YYYY-MM-DD")
			case "custom":
				return customDate.value
		}
	})

	// 判断选项是否选中
	const isSelected = (type: "today" | "tomorrow" | "custom") => {
		return selectedType.value === type
	}

	// 选择日期类型
	const selectDateType = (type: "today" | "tomorrow" | "custom", date?: string) => {
		selectedType.value = type
		if (type === "custom" && date) {
			customDate.value = date
		}
	}

	// 监听selectedDate,变化时给出提示消息
	watch(selectedDate, (newVal) => {
		// 使用dayjs判断如果为今天或明天,提示已为您筛选今日或者明日所有门票
		if (dayjs(newVal).isSame(dayjs(), "day")) {
			uni.showToast({
				title: "已为您筛选今日所有门票",
				icon: "none",
			})
		} else if (dayjs(newVal).isSame(dayjs().add(1, "day"), "day")) {
			uni.showToast({
				title: "已为您筛选明日所有门票",
				icon: "none",
			})
		} else {
			uni.showToast({
				title: `已为您筛选${dayjs(newVal).format("MM月DD日")}所有门票`,
				icon: "none",
			})
		}
	})

	return {
		selectedType,
		customDate,
		selectedDate, // 替代原来的 getSelectedDate 方法
		isSelected,
		selectDateType,
	}
}
